package com.ht.impl.myactions;

import com.ht.aems.swing.util.MyAction;
import com.ht.impl.ResourceTypeCons;
import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxIGraphModel;
import com.mxgraph.model.mxGraphModel;
import com.mxgraph.view.mxGraph;
import com.mxgraph.swing.mxGraphComponent;
import com.htgraph.layout.PathSearcher;

import java.util.*;
import java.awt.event.ActionEvent;

import org.w3c.dom.Element;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Wang Jiaxiang
 *         Date: 2010-9-19
 */
public class AutoArrange extends MyAction implements ResourceTypeCons {
    static Map<Long, mxCell> id2Graph = new HashMap<Long, mxCell>();
 
    public void actionPerformed(ActionEvent e) {
        mxGraphComponent component = (mxGraphComponent) e.getSource();
        mxGraph graph = component.getGraph();
        mxIGraphModel model = graph.getModel();
        Collection cells = ((mxGraphModel) model).getCells().values();
        if (cells.size() == 0)
            return;
        if (HideLine.lines.size() == 0) {
            for (Object o : cells) {
                mxCell mxc = null;
                if (o instanceof mxCell)
                    mxc = (mxCell) o;
                if (mxc == null)
                    continue;
                if (mxc.isEdge())
                    HideLine.lines.add(mxc);
            }
        }
        mxCell cell;
        Element element = null;
        id2Graph.clear();
        for (Object obj : cells) {
            cell = (mxCell) obj;
            try {
                element = (Element) cell.getValue();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            if (element == null)
                continue;
            String ss = element.getAttribute("CellNum");
            if (!ss.equals("") && ss != null)
                id2Graph.put((long) Integer.parseInt(ss), cell);
        }
        PathSearcher pathSearcher = new PathSearcher();
        pathSearcher.setElements(id2Graph);
        pathSearcher.setLines(HideLine.lines);
        pathSearcher.formLines();
        model.beginUpdate();
        for (mxCell line : HideLine.lines)
            model.setVisible(line, true);
        model.endUpdate();
        component.refresh();
    }
}
